package lormi.meipin.util;



import lormi.meipin.exception.LMException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URLDecoder;

public class CacheUtil {
	
	private static CacheUtil instance = null;
	
	@Autowired
	private CacheManager cacheManager;
	
	private CacheUtil(){
		try {
			cacheManager = CacheManager.create(URLDecoder.decode(getClass().getResource("/").getPath()+"ehcache.xml","utf-8"));
		} catch (Exception e) {
			throw new LMException();
		}
	}
	
	public static CacheUtil getCacheUtil(){
		if (instance == null) {
			synchronized (Object.class) {
				if (instance == null) {
					return new CacheUtil();
				}
			}
		}
		return instance;
	}
//==============登陆缓存，包括用户校验和token校验
	public Object getLoginCache(String key){
		Element element = getCacheUtil().cacheManager.getCache("loginCache").get(key);
		return element==null?null:element.getObjectValue();
	}
	
	public void setLoginCache(String key,Object value){
		getCacheUtil().cacheManager.getCache("loginCache").put(new Element(key, value));
	}

//==============城市信息缓存
	public Object getCityCache(String key){
		Element element = getCacheUtil().cacheManager.getCache("cityCache").get(key);
		return element==null?null:element.getObjectValue();
	}
	
	public void setCityCache(String key,Object value){
		getCacheUtil().cacheManager.getCache("cityCache").put(new Element(key, value));
	}

//==============其他缓存，包括部分系统参数
	public Object getOtherCache(String key){
		Element element = getCacheUtil().cacheManager.getCache("otherCache").get(key);
		return element==null?null:element.getObjectValue();
	}
	public String getOtherCacheToStr(String key){
		Element element = getCacheUtil().cacheManager.getCache("otherCache").get(key);
		if (element!=null) {
			return element.getObjectValue().toString();
		}
		return null;
	}

	public void setOtherCache(String key,Object value){
		getCacheUtil().cacheManager.getCache("otherCache").put(new Element(key, value));
	}

}
